<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12">
            <a-form-model-item label="款项名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paymentName">
              <a-input disabled v-model="model.paymentName" placeholder="请输入款项名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="需分配款项金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isAllowDistributionMoney">
              <a-input-number
                disabled
                v-model="model.isAllowDistributionMoney"
                @blur="jeBlur"
                :precision="2"
                placeholder="请输入需分配款项金额"
                :min="model.collectMoney"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="预计款项日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paymentDate">
              <j-date disabled placeholder="请选择预计款项日期" v-model="model.paymentDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="款项节点说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paymentDesc">
              <!-- <a-input :disabled=formDisabled v-model="model.paymentDesc" placeholder="请输入款项节点说明"></a-input> -->
              <a-textarea disabled v-model="model.paymentDesc" rows="4" placeholder="请输入款项节点说明" />
            </a-form-model-item>
          </a-col>
          <a-divider style="top:20px;">关联任务</a-divider>
          <a-col :span="24">
            <ErpOmcTaskRedistributionPlanTaskList
              ref="omcContractPlanTaskList"
              :disabled="disabled"
              :totalPrice="model.isAllowDistributionMoney"
              :shouldPayFlag="model.shouldPayFlag"
              :bchte="bchte"
              :redistributionDtList="redistributionDtList"
              :projectId="projectId">
            </ErpOmcTaskRedistributionPlanTaskList>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { getAction } from '@api/manage';
import ErpOmcTaskRedistributionPlanTaskList from './ErpOmcTaskRedistributionPlanTaskList'
export default {
  name: 'ErpOmcTaskRedistributionPaymentForm',
  components: {
    ErpOmcTaskRedistributionPlanTaskList
  },
  props: {
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    // 合同金额
    bchte: {
      type: Number,
      default: 0
    },
    projectId: {
      type: [String, Number],
      default: '',
      required: false
    },
    // 分配任务信息列表
    redistributionDtList: {
      type: [Array],
      default: () => []
    }

  },
  data() {
    return {
      warnShow: false,
      // 最大和输入金额
      model: {},
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        paymentName: [
          { required: true, message: '请选择款项名称!' }
        ],
        paymentMoney: [
          { required: true, pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的金额!' }
        ],
        isAllowDistributionMoney: [
          { required: true, pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的金额!' }
        ],
        paymentDate: [
          { required: true, message: '请选择预计款项日期!' }
        ],
        paymentDesc: [
          { required: true, message: '请选择款项节点说明!' }
        ]
      },
      url: {
        add: '/api/erp/omc/contractmanager/erpOmcContractManagerPlan/add',
        edit: '/api/erp/omc/contractmanager/erpOmcContractManagerPlan/edit',
        queryById: '/api/erp/omc/contractmanager/erpOmcContractManagerPlan/queryById',
        queryByApplyId: '/api/erp/omc/contractmanager/erpOmcContractManagerPlanFinal/queryByApplyId'
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    add() {
      this.edit(this.modelDefault);
    },
    edit(record) {
      this.$refs['form'].clearValidate();
      this.warnShow = false
      Object.assign(this.$data, this.$options.data())
      // this.$refs.form.resetFields();
      this.model = Object.assign({}, record);
      if (record.planTaskVoList && record.planTaskVoList.length) {
        record.planTaskVoList.forEach((item, index) => {
          item.key = index
        })
      }

      this.$refs.omcContractPlanTaskList.dataSource = record.planTaskVoList ? (JSON.parse(JSON.stringify(record.planTaskVoList))) : []
      if (this.model.id) {
        this.$refs.omcContractPlanTaskList.planId = this.model.planId
      } else {
        this.$refs.omcContractPlanTaskList.planId = ''
      }
      if (this.model.collectMoney) {
        this.warnShow = true
      } else {
        if (this.model.id) {
          // 查看合同档案
          getAction(this.url.queryByApplyId, { sealId: this.model.id }).then((res) => {
            if (res.success) {
              // this.dataSource = res.result.records || res.result
              this.model.collectMoney = (res.result && res.result.collectMoney) ? res.result.collectMoney : 0
              if (this.model.collectMoney) {
                this.warnShow = true
              }
            }
          })
        }
      }
      this.visible = true;
    },
    // 修改金额需要重新计算任务中的款项分配金额
    jeBlur() {
      let planTaskVoList = this.$refs.omcContractPlanTaskList.submitForm()
      if (planTaskVoList && planTaskVoList.length > 0) {
        if (this.model.isAllowDistributionMoney === null || this.model.isAllowDistributionMoney === '' || this.model.isAllowDistributionMoney === undefined) {
          planTaskVoList.forEach(item => {
            item.isAllowDistributionMoney = 0
          })
          this.$refs.omcContractPlanTaskList.dataSource = planTaskVoList
        } else {
          planTaskVoList.forEach(item => {
            let paymentRate = item.paymentRate
            let amount = this.model.isAllowDistributionMoney * paymentRate / 100
            item.isAllowDistributionMoney = Math.round((amount + Number.EPSILON) * 100) / 100;
          })
          this.$refs.omcContractPlanTaskList.dataSource = planTaskVoList
        }
      }
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          let planTaskVoList = this.$refs.omcContractPlanTaskList.submitForm()
          // 判断是否绑定任务
          if (!planTaskVoList.length > 0) {
            this.$message.warning('请添加关联任务信息！');
            this.$emit('unButtonDisable');
            return
          }
          // 判断关联的任务id不能重复
          let taskIdList = planTaskVoList.map(item => item.taskId)
          let taskIdListSet = new Set(taskIdList)
          if (taskIdList.length !== taskIdListSet.size) {
            this.$message.warning('关联任务不能重复！');
            this.$emit('unButtonDisable');
            return
          }
          let totalRate = 0
          planTaskVoList.forEach(item => {
            totalRate = Number(item.paymentRate) + totalRate
          })
          // 关联任务款项分配占比需等于100
          if (totalRate !== 100) {
            that.$message.warning('各关联任务的款项分配占比之和需要等于100%！');
            this.$emit('unButtonDisable');
            return
          }
          this.model.planTaskVoList = planTaskVoList
          this.model.taskId_dictText = '' // 首先款项关联任务字段默认为空
          this.model.shouldPayFlag = this.model.shouldPayFlag ? this.model.shouldPayFlag : '0' // 新增编辑默认就是未生成
          // 遍历planTaskList数组赋值给taskId_dictText
          this.model.taskId_dictText = planTaskVoList && planTaskVoList.length ? (planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
          if (!this.model.id) {
            this.model.id = parseInt(Math.random() * 1000000000000);
          }
          that.$emit('ok', this.model);
        }
      })
    }
  }
}
</script>
